﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Dycox.ComponentModel
{
    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void SendPropertyChanged(string propertyName)
        {
            if (_changedProperties != null)
            {
                if (!_changedProperties.Contains(propertyName))
                    _changedProperties.Add(propertyName);
            }
            else
                OnPropertyChagned(new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void OnPropertyChagned(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }

        StringCollection _changedProperties;
        /// <summary>
        /// Suspends raising <see cref="PropertyChanged"/> event unitl <see cref="ResumePropertyChanged"/> called.
        /// </summary>
        public void SuspendPropertyChanged()
        {
            if (_changedProperties == null)
                _changedProperties = new StringCollection();
        }

        /// <summary>
        /// Resumes raising <see cref="PropertyChanged"/> event. If any properties changed since last call of <see cref="SuspendPropertyChanged"/>, 
        /// the <see cref="PropertyChanged"/> event will be raised.
        /// </summary>
        /// <param name="sendOnce">Indicates how <see cref="PropertyChanged"/> event been raised. If true,
        /// each property that changed will raise its coresponding <see cref="PropertyChanged"/> event, otherwise,
        /// only one <see cref="PropertyChanged"/> event will be raised, and the <see cref="PropertyChangedEventArgs.PropertyName"/> would set to null.</param>
        public void ResumePropertyChanged(bool sendOnce)
        {
            if (_changedProperties != null)
            {
                if (!sendOnce)
                {
                    foreach (string name in _changedProperties)
                        OnPropertyChagned(new PropertyChangedEventArgs(name));
                }
                else if (_changedProperties.Count > 0)
                    OnPropertyChagned(new PropertyChangedEventArgs(null));
                _changedProperties = null;
            }
        }

        /// <summary>
        /// Resumes raising <see cref="PropertyChanged"/> event. If any properties changed since last call of <see cref="SuspendPropertyChanged"/>, 
        /// one <see cref="PropertyChanged"/> event will be raised, and the <see cref="PropertyChangedEventArgs.PropertyName"/> would set to null.
        /// </summary>
        public void ResumePropertyChanged()
        {
            ResumePropertyChanged(false);
        }
    }
}
